package com.yijiajiao.finance.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.yijiajiao.finance.bean.ResultBean;
import com.yijiajiao.finance.bean.TeacherMoney;
import com.yijiajiao.finance.mappers.FinanceLogMapper;
import com.yijiajiao.finance.mappers.SettleAccountsMapper;
import com.yijiajiao.finance.mappers.TeacherMoneyMapper;
import com.yijiajiao.finance.service.TeacherMoneyService;
import com.yijiajiao.finance.util.Config;
import com.yijiajiao.finance.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @AUTHOR zhaoming@eduspace
 * @CREATE 2017-05-10-11:22
 */
@Service("teacherMoneyService")
public class TeacherMoneyServiceImpl implements TeacherMoneyService {
    private static Logger log = LoggerFactory.getLogger(TeacherMoneyServiceImpl.class);
    @Autowired
    private FinanceLogMapper financeLogMapper;
    @Autowired
    private TeacherMoneyMapper teacherMoneyMapper;
    @Autowired
    private SettleAccountsMapper settleAccountsMapper;

    @Override
    public ResultBean getRemainMoney(String openId) {

        TeacherMoney teacherMoney = teacherMoneyMapper.queryTeacherMoneyByOpenId(openId);
        if (teacherMoney == null) {
            //无数据
            teacherMoney = new TeacherMoney();
            teacherMoney.setOpenId(openId);
            return ResultBean.getSucResult(teacherMoney);
        }

        //获得本月第一天
        Date firstDay = DateUtil.calcBeginMonth(DateUtil.getNowTime());
        //获得本月结算日期
        Date deadline = DateUtil.calcDate(firstDay, 5, Config.getInt("deadline")-1);
        Date now = new Date();
        Map<String, Object> param = new HashMap<>();
        param.put("openId", openId);
        if(now.getTime()>= firstDay.getTime() && now.getTime() < deadline.getTime()){
            log.info("查询日期在本月1号到11号0点之前，本期余额为上个月收入");
            param.put("date", DateUtil.calcDate(firstDay, 2, -1));
        }else {
            log.info("查询日期在本月11号0点到月末之前，本期余额为本月收入");
            param.put("date", now);
        }
        BigDecimal income = financeLogMapper.queryAllTeacherIncomeByMonth(param);
        teacherMoney.setWithdrawalCash(income);
        log.info("查询数据为 " + teacherMoney);
        return ResultBean.getSucResult(teacherMoney);
    }

}
